<template>
  <div />
</template>

<script>
export default {
  name: "Websocket",
  data() {
    return {
      path: `wss://hkchatgpt.yl1001.com`,
      // path:"ws://192.168.0.200:8005/qrCodePage/ID=1/refreshTime=5",
      socket: "",
      columnName: null,
      messageCallback: null,
      errorCallback: null,
    };
  },
  mounted() {
    // 初始化,在校园版不需要编辑，所以注释了Init
    // this.init()
  },
  destroyed() {
    // 销毁监听
    // this.socket.onclose = this.close;
    // this.socket.close();
  },
  methods: {
    init: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;

        this.socket.onclose = this.close;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      //console.log("socket连接成功");
    },
    error: function () {
      this.$message({
        type: "fail",
        message: "连接AI失败，请F5刷新该页面!",
      });
      //console.log("连接错误");
    },
    getMessage: function (msg) {
      // console.log('返回数据')
      let res = "";
      try {
        if (msg.data) {
          res = JSON.parse(msg.data);
        }
      } catch (error) {
        res = "err";
      }
      this.messageCallback = res;
      // this.$parent.initMessageBack(res)
      this.$emit("initMessageBack", res);
      return res;
    },
    send: function (agentData, successCallback, errCallback) {
      // console.log(agentData)
      this.messageCallback = successCallback;
      this.errorCallback = errCallback;
      this.socket.send(agentData);
    },
    close: function () {
      //console.log("socket已经关闭");
    },
  },
};
</script>

<style>
</style>
